package com.hanhai.zrb.backend.web.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.hanhai.common.enums.ErrorCode;
import com.hanhai.common.file.fastdfs.StorePath;
import com.hanhai.common.file.fastdfs.service.IStorageClientService;
import com.hanhai.common.file.fastdfs.service.ITrackerClientService;
import com.hanhai.common.util.Image;
import com.hanhai.common.web.controller.BaseController;
import com.hanhai.zrb.api.biz.service.PhotoService;
import com.hanhai.zrb.backend.util.MultipartFileValidator;
import com.hanhai.zrb.model.photo.Photo;
import com.hanhai.zrb.model.photo.PhotoStatusEnum;

@Controller
@RequestMapping("image")
public class ImageController extends BaseController {

	@Autowired
	private ITrackerClientService trackerClientService;

	@Autowired
	private IStorageClientService storageClientService;

	@Resource
	private PhotoService photoService;

	// @PermissionNeed("project")
	@RequestMapping("uploadImg")
	public void uploadImg(MultipartHttpServletRequest request,
			HttpServletResponse response, Long bizid,Integer type) {
		MultipartFile file = request.getFile("file");
		MultipartFileValidator validator = new MultipartFileValidator();
		validator.setAllowedContentTypes(new String[] { "image/jpeg",
				"image/pjpeg", "image/png", "image/x-png" });
		String path = null;
		String name = null;
		try {
			if (null != file && !file.isEmpty()) {
				long fileSize=file.getSize();
				if(fileSize>200*1024){
					super.jsonFail(response, "图片大小不能超过200kb~");
					return;
				}
				name = file.getOriginalFilename();
				validator.validate(file);
				path = storeFile(file);
				storeSlaveFile(file, path);
			} else {
				super.jsonFail(response, "图片文件为空~");
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			super.jsonFail(response, "图片格式不正确或大小超过限制，"+e.getMessage());
			return;
		}

		Long id = null;
		if (bizid != null) {
			// 临时图片存起来
			Photo photo = new Photo();
			photo.setName(name);
			photo.setUrl(path);
			photo.setBizid(bizid);
			photo.setStatus(PhotoStatusEnum.TEMP.getCode());
			photo.setType(type);
			id = photoService.add(photo);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", ErrorCode.OK.getCode());
		jsonObject.put("path", path);
		jsonObject.put("name", name);
		if (id != null) {
			jsonObject.put("id", id);
		}
		super.returnJsonObject(response, jsonObject);
	}

	private String storeSlaveFile(MultipartFile file, String filename)
			throws IOException {
		String fileName = file.getOriginalFilename();
		File newfile = new File(fileName);
		file.transferTo(newfile);
		Image image = new Image(newfile);
		image.resize(160, 120);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		image.converToByte("jpg", baos);

		byte[] bytes = baos.toByteArray();
		StorePath storePath = storageClientService.uploadSlaveFile("group1",
				filename.substring(filename.indexOf("/") + 1),
				new ByteArrayInputStream(bytes), bytes.length, "_160x120",
				"jpg");
		String finalPath= storePath.getGroup() + "/" + storePath.getPath();
		if(file != null){
			newfile.delete();
		}
		return finalPath;
	}

	private String storeFile(MultipartFile file) throws IOException {
		byte[] bytes = file.getBytes();
		StorePath storePath = storageClientService.uploadFile("group1",
				new ByteArrayInputStream(bytes), bytes.length, "jpg");
		return storePath.getGroup() + "/" + storePath.getPath();
	}
}
